package nckd.wnqjt.tmc.tda.plugin.form;

import com.alibaba.fastjson.JSON;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.qing.*;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import org.apache.batik.css.engine.value.StringValue;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 结算金额轻分析报表（个体折线图）
 */

public class TlementTrendQingQueryPlugin extends AbstractFormPlugin implements IQingDataProvider {

    //收款单源单类型
    private String[] recBillType = {"fca_transdownbill","fca_transupbill"};
    //付款单源单类型
    private String[] payBillType = {"Qyhkd","Qyfxd","Qydkfkd"};
    //组织形态
    private String[] orgType = {"部门","工厂","集团","集团公司","事业部"};

    @Override
    public QingMeta getMeta(String s) {
        String entityKey = "cas_recbill";
        QingMeta meta = new QingMeta();
        EntryEntity entity1 = new EntryEntity();
        entity1.setKey(entityKey);
        entity1.setName(new LocaleString("收款处理"));
        entity1.setPkFieldName("id");
        meta.addEntryEntity(entity1);

        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("id");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Int.toNumber()); //数据类型	是
        column.setName(new LocaleString("id")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("inflow");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.Number.toNumber()); //数据类型	是
        column.setName(new LocaleString("本月流入")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("outflow");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("本月流出"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("claninflow");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("本月净流入"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("month");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("月份"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("orgName");
        column.setFieldType(QingFieldType.String.toNumber());
        column.setName(new LocaleString("组织"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("siz");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("计数字段"));
        meta.addColumn(column);
        return meta;
    }

    @Override
    public QingData getData(String s, int startRow, int i1) {
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }
        QFilter[] billFilters = null;
        //单据状态=审核
        QFilter qFilter1 = new QFilter("billstatus", QCP.equals,"D");
        //源单类型剔除“上划单”与“下拨单
        QFilter qFilter2 = new QFilter("sourcebilltype", QCP.not_in,recBillType);
        //结算方式为空
        QFilter settletnumberFilter = new QFilter("settletnumber", QCP.not_equals,"1");

        DataSet result = null;
        for (int i = 0; i < 12; i++) {
            /*
        收款单
         */
            String month = "'"+(i+1)+"月"+"'";

            QFilter dateQf = new QFilter("payeedate", QCP.large_equals, DateUtils.getMinMonth(i+1)).and(new QFilter("payeedate", QCP.less_equals, DateUtils.getMaxMonth(i+1)));
            billFilters = new QFilter[]{qFilter1,qFilter2,dateQf,settletnumberFilter};
            String recBillFiled = "id,billstatus,sourcebilltype,actrecamt,settletnumber,org,org.id as recOrgId,org.name as orgName,payeedate";
            DataSet recBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_recbill", recBillFiled, billFilters, null);
            recBillData = recBillData.groupBy(new String[]{"orgName","recOrgId"}).sum("actrecamt").finish();

        /*
        付款单
         */
            qFilter2 = new QFilter("nckd_sourcebilltype", QCP.not_in,payBillType);
            QFilter qFilter3 = new QFilter("sourcetype", QCP.not_equals,"FCA");
            dateQf = new QFilter("paydate", QCP.large_equals, DateUtils.getMinMonth(i+1)).and(new QFilter("paydate", QCP.less_equals, DateUtils.getMaxMonth(i+1)));
            billFilters = new QFilter[]{qFilter1, qFilter2,qFilter3,dateQf,settletnumberFilter};
            String payBillFiled = "id,billstatus,settletnumber,org,org.id as payOrgId,org.name as orgName,sourcetype,paydate,actpayamt";//nckd_sourcebilltype,
            DataSet payBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_paybill", payBillFiled, billFilters, null);
            payBillData = payBillData.groupBy(new String[]{"orgName","payOrgId"}).sum("actpayamt").finish();
        /*
        代发单
         */
            String agentBillFiled = "id,billstatus,actpayamount,settletnumber,org,org.id as agentOrgId,org.name as orgName,paytime";
            dateQf = new QFilter("paytime", QCP.large_equals, DateUtils.getMinMonth(i+1)).and(new QFilter("paytime", QCP.less_equals, DateUtils.getMaxMonth(i+1)));
            billFilters = new QFilter[]{qFilter1,dateQf,settletnumberFilter};
            DataSet agentBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cas_agentpaybill", agentBillFiled, billFilters, null);
            agentBillData.groupBy(new String[]{"orgName","agentOrgId"}).sum("actpayamount").finish();

        /*
        业务单元
         */
            String orgFiled = "id,name,orgpattern,orgpattern.name";
            QFilter qFilter4 = new QFilter("orgpattern.name", QCP.not_in,orgType);
            billFilters = new QFilter[]{qFilter4};
            DataSet orgBillData = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bos_org", orgFiled, billFilters, null);

            DataSet dataSet = orgBillData.leftJoin(recBillData).on("id", "recOrgId").select(new String[]{"id", "name"},new String[]{"recOrgId","actrecamt"}).finish();
            DataSet dataSet1 = dataSet.leftJoin(payBillData).on("id","payOrgId").select(new String[]{"id","name","actrecamt"},new String[]{"payOrgId","actpayamt"}).finish();
            DataSet dataSet2 = dataSet1.leftJoin(agentBillData).on("id","agentOrgId").select(new String[]{"id","name","actrecamt","actpayamt"},new String[]{"agentOrgId","actpayamount"}).finish();
            dataSet2 = dataSet2.addField(month,"month").addField(String.valueOf(i),"siz");
            if (result == null){
                result = dataSet2;
            }else {
                result = result.union(dataSet2);
            }
        }


        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            dataindex.put("id", 0);
            dataindex.put("inflow", 1);
            dataindex.put("outflow", 2);
            dataindex.put("claninflow", 3);
            dataindex.put("orgName", 4);
            dataindex.put("month", 5);
            dataindex.put("siz", 6);
            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            while (result.hasNext()) {
                Row row = result.next();
                Object[] obj = new Object[7];
                obj[0] = row.getLong("id");
                BigDecimal actrecamt = row.getBigDecimal("actrecamt") == null ? BigDecimal.ZERO : row.getBigDecimal("actrecamt");
                BigDecimal actpayamt = row.getBigDecimal("actpayamt") == null ? BigDecimal.ZERO : row.getBigDecimal("actpayamt");
                BigDecimal actpayamount = row.getBigDecimal("actpayamount") == null ? BigDecimal.ZERO : row.getBigDecimal("actpayamount");
                obj[1] = actrecamt;
                obj[2] = actpayamt.add(actpayamount);
                //Timestamp timestamp = (Timestamp) row.get("bizdate");
                //long time = timestamp.getTime();
                obj[3] = actrecamt.subtract(actpayamt.add(actpayamount));
                obj[4] = row.getString("name");
                obj[5] = row.getString("month");
                obj[6] = row.getInteger("siz");
                rows.add(obj);
            }
            data.setRows(rows);
        }
        return data;
    }

    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }





}
